#!/bin/bash

#此脚本用于全量、差异备份数据库和恢复最近一次备份的数据
#参数full_back为全量，zl_back为差异，restore为恢复
day=`date  +%Y-%m-%d-%H-%M-%S`
mysql_password='1qaz2WSX~'
back_use='root'
mysql_db='lsw'
back_full_dir='/data/backup/full'
back_zl_dir='/data/backup/zl'
back_tar='/data/backup/tar'
mysql_cnf='/etc/my.cnf'
DB='LSW'
#TIME=`ls --full-time|awk '{print $6,$9}'|sort -r -n |head -n 1|awk '{print $2}'`
full_back () { echo "Start backup ...." `date +%F-%H:%M:%S` >> /tmp/mysqlbak.log
########执行完全备份############
if [ ! -e ${back_full_dir} ];then
	mkdir -p ${back_full_dir}
	echo "mkdir ${back_full_dir} ok!"
fi
#####备份命令#######
######如果指定单个库的话加上--databases=$DB，在从库备份要加上--slave-info
innobackupex --defaults-file=${mysql_cnf} --user=${back_use} --password=${mysql_password}  ${back_full_dir}
if [ ! $? = 0 ];then
	echo  "Backup failure....Please check......." `date +%F-%H:%M:%S` >> /tmp/mysqlbak.log
	exit 2
fi
########把备份文件打包并保存到别的目录##########
cd ${back_full_dir}
if [ ! -e ${back_tar} ];then
	mkdir -p ${back_tar}
	echo "mkdir ${back_tar} ok!"
fi
tar -cvzf ${back_tar}/fullback-${day}.tar.gz `ls -t ${back_full_dir} |sort -r -n |head -n 1`
if [ $? = 0 ];then
	echo "Backup complete.."`date +%F-%H:%M:%S` >> /tmp/mysqlbak.log
fi
}

cy_back () { echo "Start backup..."`date +%F-%H:%M:%S` >> /tmp/mysqlzlbak.log
#######执行差异备份#########
if [ ! -e  ${back_zl_dir} ];then 
	mkdir -p ${back_zl_dir}
	echo "mkdir ${back_zl_dir} ok!"
fi
cd ${back_full_dir}
innobackupex --user=${back_use} --password=${mysql_password} --incremental ${back_zl_dir} --incremental-basedir=`ls -t ${back_full_dir} |sort -r -n |head -n 1`
if [ $? = 0 ];then
	echo "Backup complete.."`date +%F-%H:%M:%S` >> /tmp/mysqlzlbak.log
else
	echo "Backup failure....Please check........."`date +%F-%H:%M:%S` >> /tmp/mysqlzlbak.log
fi

}
######恢复数据库#######
restore () {
######停止mysql服务######
service mysqld stop
######准备恢复文件######
innobackupex --defaults-file=${back_full_dir}/`ls -t ${back_full_dir}|sort -r -n |head -n 1`/backup-my.cnf --apply-log --redo-only ${back_full_dir}/`ls -t ${back_full_dir}|sort -r -n |head -n 1`
if [ $? = 0 ];then
	echo "########全量文件已经准备完毕#######"
else
	echo "#######请检查全量恢复文件#########"
	exit 3
fi
innobackupex --defaults-file=${back_full_dir}/`ls -t ${back_full_dir}|sort -r -n |head -n 1`/backup-my.cnf --apply-log --redo-only ${back_full_dir}/`ls -t ${back_full_dir}|sort -r -n |head -n 1` --incremental-dir=${back_zl_dir}/`ls -t ${back_zl_dir}|sort -r -n |head -n 1`
if [ $? = 0 ];then
        echo "########差异文件已经准备完毕#######"
else
        echo "#######请检查差异恢复文件#########"
        exit 4
fi

#####开始恢复########
innobackupex --copy-back ${back_full_dir}/`ls -t ${back_full_dir}|sort -r -n |head -n 1`
if [ $? = 0 ];then
        echo "########恢复成功#######"
else
        echo "#######恢复出了问题请检查...........#########"
        exit 5
fi

######自己手动修改权限并恢复二进制日志###########

}
case $1 in
cy_back)
	zl_back
	;;
full_back)
	full_back
	;;
restore)
	restore
	;;
*)
	echo "Usage: $0 {full_back|cy_back|restore}" 
	;;
esac

